import { getUserInfo, login } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { getUserDetailByid } from '@/api/employees'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    UserInfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
    },
    // 移除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    //  保存用户信息
    setUserInfo(state, UserInfo) {
      state.UserInfo = UserInfo
    },
    // 移除用户信息
    removeUserInfo(state) {
      state.UerInfo = {}
    }
  },
  actions: {
    async login(store, data) {
      const result = await login(data)
      // console.log('11111', result)
      store.commit('setToken', result)

      // 保存token到本地缓存
      setToken(result)
      //  保存本地时间戳
      localStorage.setItem('loginTime', Date.now())
    },
    //  获取用户资料
    async getUserInfo(store) {
      const result = await getUserInfo()
      // 获取员工基本信息
      const res = await getUserDetailByid(result.userId)
      // console.log('29', result)
      // 合并用户信息
      store.commit('setUserInfo', { ...result, ...res })
    },
    // 封装退出登录函数 调用即可
    logout(store) {
      store.commit('removeToken')
      store.commit('removeUserInfo')
    }
  }
}

